package net.luohuasheng.bee.proxy.core.utils;

import net.luohuasheng.bee.proxy.core.enums.PrimitiveType;

import java.lang.reflect.Array;
import java.util.Objects;

/**
 * @author luohuasheng
 * @date 2020/4/10 15:55
 */
public class CastUtils {
    @SuppressWarnings("unchecked")
    public static <T> T cast(Object obj) {
        if (obj != null && obj.getClass().isArray()) {
            Class<?> type = obj.getClass().getComponentType();
            if (type.isPrimitive()) {
                Class<?> classZ = Objects.requireNonNull(PrimitiveType.getType(type)).getClassZ();
                int length = Array.getLength(obj);
                Object array = Array.newInstance(classZ, length);
                for (int i = 0; i < length; i++) {
                    Array.set(array, i, Array.get(obj, i));
                }
                obj = array;
            }
        }
        return (T) obj;
    }
}
